const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');

// 添加游戏状态变量
let gameStarted = false;
let gameLoop; // 游戏循环的定时器

// 获取开始按钮和游戏结束信息
const startButton = document.getElementById('startButton');
const gameOverEl = document.getElementById('gameOver');

// 加载图片
const playerImg = new Image();
playerImg.src = 'player.png'; // 玩家飞机图片
const enemyImg = new Image();
enemyImg.src = 'enemy.png'; // 敌机图片

const player = {
    x: canvas.width / 2,
    y: canvas.height - 100,
    width: 50,
    height: 50,
    speed: 5,
    bullets: []
};

const enemy = {
    width: 50,
    height: 50,
    speed: 2,
    list: []
};

let score = 0;

// 按键状态对象
const keyState = {
    left: false,
    right: false,
    space: false
};

// 爆炸效果数组
let explosions = [];

function drawPlayer() {
    ctx.drawImage(playerImg, player.x, player.y, player.width, player.height);
}

function movePlayer() {
    if (keyState.left && player.x > 0) {
        player.x -= player.speed;
    }
    if (keyState.right && player.x < canvas.width - player.width) {
        player.x += player.speed;
    }
}

function shootBullet() {
    if (keyState.space) {
        player.bullets.push({
            x: player.x + player.width / 2 - 2.5, // Center the bullet
            y: player.y,
            width: 5,
            height: 15,
            color: '#FFFF00',
            speed: 10
        });
        keyState.space = false; // 防止持续发射
    }
}

function drawBullets() {
    player.bullets.forEach((bullet, index) => {
        // 绘制子弹尾迹
        ctx.strokeStyle = '#FFFF00';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(bullet.x + bullet.width / 2, bullet.y + bullet.height);
        ctx.lineTo(bullet.x + bullet.width / 2, bullet.y + bullet.height + 10);
        ctx.stroke();

        // 绘制子弹主体
        ctx.fillStyle = '#FFFF00';
        ctx.beginPath();
        ctx.arc(bullet.x + bullet.width / 2, bullet.y, bullet.width / 2, 0, Math.PI * 2);
        ctx.fill();

        // 更新子弹位置
        bullet.y -= bullet.speed;

        // 如果子弹超出屏幕范围，移除它
        if (bullet.y < 0) {
            player.bullets.splice(index, 1);
        }
    });
}

function createEnemy() {
    enemy.list.push({
        x: Math.random() * (canvas.width - enemy.width),
        y: -enemy.height,
        width: enemy.width,
        height: enemy.height
    });
}

function drawEnemies() {
    enemy.list.forEach((e, index) => {
        ctx.drawImage(enemyImg, e.x, e.y, e.width, e.height);
        e.y += enemy.speed;

        if (e.y > canvas.height) {
            enemy.list.splice(index, 1);
        }

        // Check collision with player
        if (e.y + e.height > player.y && e.x < player.x + player.width && e.x + e.width > player.x) {
            gameOver();
        }

        // Check collision with bullets
        player.bullets.forEach((bullet, bIndex) => {
            if (bullet.y < e.y + e.height && bullet.y + bullet.height > e.y && bullet.x < e.x + e.width && bullet.x + bullet.width > e.x) {
                // 添加爆炸效果
                explosions.push({
                    x: e.x + e.width / 2,
                    y: e.y + e.height / 2,
                    particles: generateExplosionParticles(e.x + e.width / 2, e.y + e.height / 2)
                });
                enemy.list.splice(index, 1);
                player.bullets.splice(bIndex, 1);
                score += 10;
                updateScore();
            }
        });
    });
}

function updateScore() {
    scoreEl.textContent = `Score: ${score}`;
}

// 游戏结束
function gameOver() {
    clearInterval(gameLoop); // 停止游戏循环
    gameStarted = false; // 设置游戏状态为未开始
    gameOverEl.style.display = 'block'; // 显示“再来一次”信息
    startButton.style.display = 'block'; // 显示开始按钮
    startButton.textContent = '再来一次'; // 修改按钮文本为“再来一次”

    // 点击“再来一次”按钮后重新开始游戏
    startButton.addEventListener('click', () => {
        gameOverEl.style.display = 'none'; // 隐藏“再来一次”信息
        initializeGame(); // 重新初始化游戏
        gameStarted = true; // 设置游戏状态为已开始
        startGameLoop(); // 重新启动游戏循环
    });
}

// 生成爆炸粒子
function generateExplosionParticles(x, y) {
    const particles = [];
    for (let i = 0; i < 30; i++) {
        particles.push({
            x: x,
            y: y,
            radius: Math.random() * 5 + 2,
            color: `hsl(${Math.random() * 360}, 100%, 50%)`,
            velocity: {
                x: (Math.random() - 0.5) * 6,
                y: (Math.random() - 0.5) * 6
            },
            life: Math.random() * 30 + 20
        });
    }
    return particles;
}

// 绘制爆炸效果
function drawExplosions() {
    explosions = explosions.filter((explosion) => {
        explosion.particles = explosion.particles.filter((particle) => {
            ctx.beginPath();
            ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
            ctx.fillStyle = particle.color;
            ctx.fill();

            particle.x += particle.velocity.x;
            particle.y += particle.velocity.y;
            particle.life -= 1;

            return particle.life > 0;
        });

        return explosion.particles.length > 0;
    });
}

// 监听按键事件
document.addEventListener('keydown', (event) => {
    if (!gameStarted) return; // 如果游戏未开始，忽略按键
    switch (event.key) {
        case 'ArrowLeft':
            keyState.left = true;
            break;
        case 'ArrowRight':
            keyState.right = true;
            break;
        case ' ':
            keyState.space = true;
            break;
    }
});

document.addEventListener('DOMContentLoaded', () => {
    const startButton = document.getElementById('startGameButton');
    const homePage = document.getElementById('homePage');
    const gameCanvas = document.getElementById('gameCanvas');
    const scoreEl = document.getElementById('score');
    const gameOverEl = document.getElementById('gameOver');

    // 点击“开始游戏”按钮后切换到游戏内容
    startButton.addEventListener('click', () => {
        gameStarted = true;
        homePage.style.display = 'none'; // 隐藏首页
        gameCanvas.style.display = 'block'; // 显示游戏画布
        scoreEl.style.display = 'block'; // 显示分数
        initializeGame(); // 初始化游戏
        startGameLoop(); // 启动游戏循环
    });

    // 初始化游戏
    function initializeGame() {
        score = 0; // 重置分数
        updateScore();
        player.bullets = []; // 清空子弹数组
        enemy.list = []; // 清空敌机数组
        explosions = []; // 清空爆炸效果数组
        player.x = gameCanvas.width / 2 - player.width / 2; // 重置玩家位置
        player.y = gameCanvas.height - 100;
    }

    // 启动游戏循环
    function startGameLoop() {
        gameLoop = setInterval(() => {
            ctx.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
            movePlayer();
            drawPlayer();
            shootBullet();
            drawBullets();
            drawEnemies();
            drawExplosions();

            if (Math.random() > 0.98) {
                createEnemy();
            }
        }, 16); // 16ms per frame (约60 FPS)
    }

    // 游戏结束
    function gameOver() {
        clearInterval(gameLoop); // 停止游戏循环
        gameOverEl.style.display = 'block'; // 显示 GAME OVER
        startButton.style.display = 'block'; // 显示开始按钮
        startButton.textContent = '再玩一次'; // 修改按钮文本
        startButton.addEventListener('click', restartGame, { once: true }); // 使用一次性监听器; 
    }

    // 更新分数
    function updateScore() {
        scoreEl.textContent = `Score: ${score}`;
    }

    // 重新开始游戏
    function restartGame() {
        gameOverEl.style.display = 'none'; // 隐藏“再来一次”信息
        startButton.style.display = 'none'; // 隐藏开始按钮
        initializeGame(); // 重新初始化游戏
        gameStarted = true; // 设置游戏状态为已开始
        startGameLoop(); // 重新启动游戏循环
    }

    // 点击“再来一次”按钮后重新开始游戏
    restartButton.addEventListener('click', restartGame);
});





document.addEventListener('keyup', (event) => {
    if (!gameStarted) return; // 如果游戏未开始，忽略按键
    switch (event.key) {
        case 'ArrowLeft':
            keyState.left = false;
            break;
        case 'ArrowRight':
            keyState.right = false;
            break;
        case ' ':
            keyState.space = false;
            break;
    }
});

gameLoop = setInterval(() => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    movePlayer();
    drawPlayer();
    shootBullet();
    drawBullets();
    drawEnemies();
    drawExplosions(); // 绘制爆炸效果

    if (Math.random() > 0.98) {
        createEnemy();
    }
}, 16); // 16ms per frame (about 60 FPS)


// 添加开始按钮点击事件
// 开始按钮点击事件
startButton.addEventListener('click', () => {
    if (!gameStarted) {
        gameStarted = true; // 设置游戏状态为已开始
        startButton.style.display = 'none'; // 隐藏开始按钮
        gameOverEl.style.display = 'none'; // 隐藏游戏结束信息
        initializeGame(); // 初始化游戏
        startGameLoop(); // 启动游戏循环
    }
});

// 初始化游戏
function initializeGame() {
    score = 0; // 重置分数
    updateScore();
    player.bullets = []; // 清空子弹数组
    enemy.list = []; // 清空敌机数组
    explosions = []; // 清空爆炸效果数组
    player.x = canvas.width / 2 - player.width / 2; // 重置玩家位置
    player.y = canvas.height - 100;
}


function startGameLoop() {
    gameLoop = setInterval(() => {
        if (!gameStarted) return; // 如果游戏未开始，跳过循环
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        movePlayer();
        drawPlayer();
        shootBullet();
        drawBullets();
        drawEnemies();
        drawExplosions();

        if (Math.random() > 0.98) {
            createEnemy();
        }
    }, 16); // 16ms per frame (约60 FPS)
}


// 修改按键事件监听逻辑，仅在游戏开始时处理按键
document.addEventListener('keydown', (event) => {
    if (!gameStarted) return; // 如果游戏未开始，忽略按键
    switch (event.key) {
        case 'ArrowLeft':
            keyState.left = true;
            break;
        case 'ArrowRight':
            keyState.right = true;
            break;
        case ' ':
            keyState.space = true;
            break;
    }
});

document.addEventListener('keyup', (event) => {
    if (!gameStarted) return; // 如果游戏未开始，忽略按键
    switch (event.key) {
        case 'ArrowLeft':
            keyState.left = false;
            break;
        case 'ArrowRight':
            keyState.right = false;
            break;
        case ' ':
            keyState.space = false;
            break;
    }
});


